﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using CardInChina.Data.Entity.Entity;

namespace CardInChina.Data.Entity.Interface
{
    //TODO: 思考如何全局优化连接数
    public class SysVerifyService
    {
        public SysVerify CreateOne(CICEntities db, int pid, int expire)
        {
            if (db == null)
                throw new ArgumentNullException("db");

            var sv = new SysVerify
            {
                Code = Guid.NewGuid().ToString(),
                ExpireAfter = expire,
                ForId = pid,
            };
            db.SysVerifies.Add(sv);
            return sv;
        }

        public SysVerify CreateOne(int pid, int expire)
        {
            using (var db = new CICEntities())
            {
                var sv = CreateOne(db, pid, expire);
                db.SaveChanges();
                return sv;
            }
        }

        public SysVerify GetOne(CICEntities db, string code)
        {
            if (db == null)
                throw new ArgumentNullException("db");

            var sv = db.SysVerifies.FirstOrDefault(p => p.Code == code);
            
            if (sv != null)
                db.SysVerifies.Remove(sv);

            return sv;
        }

        public SysVerify GetOne(string code)
        {
            using (var db = new CICEntities())
            {
                var sv = GetOne(db, code);
               
                if (sv != null)
                    db.SaveChanges();
             
                return sv;
            }
        }


    }
}
